//初始化云
wx.cloud.init({
    env:'cloud1-2gghs59h3b578579',
    traceUser:true,
  });
  //初始化云数据库
const db = wx.cloud.database();
/**
 * 数据添加功能
 * @param {String} table 表名
 * @param {Object} data 要存储的数据 
 * @returns 
 */
export const insert = ({ table,data }) => {
    return new Promise((resolve, reject) => {
        db.collection(table).add({
            data,
            success: (res) => {
                // console.log(res);
                resolve(res);
            },
            fail: (err) => {
                reject(err);
            },
        });
    });
};
/**
 * 通过openid数据查找
 * @param {Object} table  
 * @returns 
 */
export const search = ({ table, openid }) => {
    return new Promise((resolve, reject) => {
        db.collection(table).where({
            _openid: openid,
        }).get().then(res => {
            resolve(res);
        }).catch(err => {
            reject(err);
        });
    });
};
/**
 * 更新
 * @param {table} 表名 
 * @returns 
 */
export const update = ({ table, id, content, time }) => {
    return new Promise((resolve, reject) => {
        db.collection(table)
            .doc(id)
            .update({
                data: {
                    content,
                    time,
                }
            })
            .then(res => {
                console.log(res);
                resolve(res);
            })
            .catch(err => {
                console.log(err);
                reject(err);
            });
    });
};
/**
 * 删除
 * @param {table} 表名 
 * @returns 
 */
export const remove = ({ table, id }) => {
    return new Promise((resolve, reject) => {
        db.collection(table)
            .doc(id)
            .remove({
                success: (res) => {
                    resolve(res);
                },
                fail: (err) => {
                    reject(err);
                },
            });
    });
};
/**
 * 调用云函数
 * @param {Object} name 
 * @returns 
 */
export const callFunction = ({ name }) => {
    return new Promise((resolve, reject) => {
        wx.cloud.callFunction({
            name,
            success: (res) => {
                resolve(res);
            },
            fail: (err) => {
                reject(err);
            }
        })
    })
};
